import { defineStore } from 'pinia';

import { getUser, login as userLogin } from '@/api/upms/user';
import { usePermissionStore } from '@/store';
import { encryption } from '@/utils/tools';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: 'main_token', // 默认token不走权限
    userInfo: { permissions: [], sysUser: undefined, roles: [] },
  }),
  getters: {
    roles: (state) => {
      return state.userInfo?.roles;
    },
  },
  actions: {
    async login(userInfo: Record<string, string>) {
      // 登录请求流程
      const { username, password } = userInfo;
      try {
        const pwd = encryption({
          key: '4ac9929a7c9c37d8',
          password,
        });
        const data = await userLogin({
          username,
          password: pwd,
        });
        this.token = data;
      } catch (err) {
        this.token = '';
        throw err;
      }
    },
    async getUserInfo() {
      const res = await getUser();
      this.userInfo = res;
    },
    async logout() {
      this.token = '';
      this.userInfo = {};
    },
  },
  persist: {
    afterRestore: () => {
      const permissionStore = usePermissionStore();
      permissionStore.initRoutes();
    },
    key: 'user',
    paths: ['token'],
  },
});
